package com.yishun.springboot.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.protobuf.TextFormat.ParseException;
import com.yinquan.util.ResultUtils;
import com.yishun.springboot.mapper.GwsLongGangQuCrane;
import com.yishun.springboot.util.HttpUtile;
import com.yishun.springboot.util.SignatureUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;

@Service
public class GWSLongGangQuUploadCraneServiceImpl {

	@Autowired
	GwsLongGangQuCrane gwsLongGangQuCrane;
	// private String api_key = "f0328808bad1481cad0e9207c6f67947";
	// 环境：642ef1804ff04ffcb2f87de5ee5e55b4
	private static String api_key = "a684b22a61f04f5499039ee9eebdd3a1";
	private static String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
	private static String api_version = "1.0";
	private static String engCode = "XM20230098-1";
	private static String projectCode = "XM20230098";

	private static final String GWS_URL = "http://218.17.147.31:66/openapi/";

	public String uploadCraneBasic(JSONObject jsonObject) {
		JSONObject res = new JSONObject();
		String api_key = jsonObject.getString("api_key");// 秘钥
		String api_version = jsonObject.getString("api_version");
		String engCode = jsonObject.getString("engCode");
		String projectCode = jsonObject.getString("projectCode");// 项目编号
		String mon_device_man = jsonObject.getString("mon_device_man");// 监测设备厂商
		String guangdong_install_num = jsonObject.getString("guangdong_install_num");// 产权备案编号
		String projectName = jsonObject.getString("projectName");// 项目本地名称也就是我们公司数据库所存的
		String deviceCode = jsonObject.getString("deviceCode");
		String name = jsonObject.getString("name");
		JSONObject JSON = new JSONObject();
		List<Object> jsona = new ArrayList<>();
		if (StringUtils.isEmpty(api_key) || StringUtils.isEmpty(engCode) || StringUtils.isEmpty(api_version)
				|| StringUtils.isEmpty(projectCode) || StringUtils.isEmpty(guangdong_install_num)
				|| StringUtils.isEmpty(mon_device_man) || StringUtils.isEmpty(projectName)
				|| StringUtils.isEmpty(deviceCode) || StringUtils.isEmpty(name)) {
			return JSONObject.toJSONString(ResultUtils.jsonFail(400), SerializerFeature.WriteMapNullValue);
		}
		Map<String, Object> ProjectMap = gwsLongGangQuCrane.getProject(projectName);
		if (ProjectMap == null) {
			res.put("code", 401);
			res.put("msg", "请查看此项目名称是否正确，如正确则无此项目，请联系管理员添加");
			return res.toJSONString();
		} else {

			JSONObject jsono = new JSONObject();

			Long id = (Long) ProjectMap.get("intelligentsite_crane_id");
			List<Map<String, Object>> projectAll = gwsLongGangQuCrane.getProjectAll(projectName);
			if (projectAll.size() < 1) {
				gwsLongGangQuCrane.addGwsLongGangQuCrane(id, api_key, engCode, projectCode, projectName);
			}

			List<Map<String, Object>> DeviceList = gwsLongGangQuCrane.getProjectDeviceId(id);

			Map<String, Object> ma = gwsLongGangQuCrane.findCraneDeta(deviceCode);
			if (ma != null) {
				res.put("code", 401);
				res.put("msg", "此设备已添加");
				return res.toJSONString();
			}
			String device_no = UUID.randomUUID().toString().replace("-", "");// 工务署设备编号
			jsono.put("name", name);
			jsono.put("device_no", device_no);
			jsono.put("mon_device_man", mon_device_man);
			jsono.put("guangdong_install_num", guangdong_install_num);
			jsona.add(jsono);
			String date = timestamp;
			String signature = SignatureUtil.getSignature(api_key, api_version, engCode, projectCode, date,
					jsono.toJSONString());
			JSONObject param = new JSONObject();
			param.put("api_key", api_key);
			param.put("project_code", projectCode);
			param.put("eng_code", engCode);
			param.put("api_version", api_version);
			param.put("timestamp", date);
			param.put("body", jsono);
			param.put("signature", signature);
			Map<String, Object> headerMap = new HashMap<>();
			headerMap.put("ApiKey", "cdebdbeedd4f08b2b6f5c223f51c51");
			headerMap.put("Content-Type", "application/json");
			JSONObject paramMap = new JSONObject();
			paramMap.put("ProjectId", "6620");
			paramMap.put("DeviceCode", deviceCode);
			String info = null;
			try {
				info = HttpUtile.doPost("http://47.99.64.49:2000/tower/GetSettings", paramMap, headerMap);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			JSONObject json = JSONObject.parseObject(info);
			JSONArray jsonArray = json.getJSONArray("Data");
			if (jsonArray.size() < 1) {
				res.put("code", 400);
				res.put("msg", "GetSettings基础数据为空，请联系管理人员添加！！！！！");
				return res.toJSONString();
			}
			json = jsonArray.getJSONObject(0);

			Double TC_MaxScope = json.getDouble("MaxRange");
			Double TC_MaxHeight = json.getDouble("MaxHeight");
			Double TC_LoadCapacity = json.getDouble("MaxWeight");
			if (deviceCode == null || name == null || TC_MaxScope == null || TC_MaxHeight == null
					|| TC_LoadCapacity == null) {
				json = new JSONObject();
				json.put("code", 401);
				json.put("msg", "设备参数不能为空");
			}
			info = HttpUtil.post(GWS_URL + "crane/addBasicInfo", param.toJSONString());

			gwsLongGangQuCrane.addCraneInfo(id, name, deviceCode, device_no, guangdong_install_num);

			double load_moment = TC_MaxScope * TC_LoadCapacity;
			JSON.put("device_no", device_no);
			JSON.put("name", name);
			JSON.put("TC_MaxScope", TC_MaxScope);
			JSON.put("TC_MaxHeight", TC_MaxHeight);
			JSON.put("TC_LoadCapacity", TC_LoadCapacity);
			JSON.put("load_moment", load_moment);
			jsona.remove(0);
			jsona.add(JSON);
			param.put("body", JSON);
			date = timestamp;
			param.put("timestamp", date);
			signature = SignatureUtil.getSignature(api_key, api_version, engCode, projectCode, date,
					JSON.toJSONString());
			param.put("signature", signature);
			info = HttpUtil.post(GWS_URL + "/crane/addParams", param.toJSONString());
			return info;
		}

	}

	@Async(value = "asyncExecutor")
	@Scheduled(fixedRate = 1000 * 60)
	public void addRecord() {
		List<Map<String, Object>> projectAll = gwsLongGangQuCrane.getProjectAll(null);
		for (Map<String, Object> li : projectAll) {
			Integer id = (Integer) li.get("project_id");

			String api_key = li.get("api_key").toString();// 秘钥
			String engCode = li.get("engCode").toString();
			String projectCode = li.get("projectCode").toString();// 项目编号
			List<Map<String, Object>> deviceList = gwsLongGangQuCrane.getProjectDeviceAll(id);
			for (Map<String, Object> lis : deviceList) {
				Map<String, Object> resMap = gwsLongGangQuCrane.getDeviceVal(lis.get("deviceCode").toString());
				String runtime = resMap.get("RunTime").toString();
				double load = (double) resMap.get("Weight");
				double load_ratio = (double) resMap.get("WeightPercent");
				Float moment = (Float) resMap.get("Moment");
				double moment_ratio = (double) resMap.get("MomentPercent");
				double slewing_speed = (double) resMap.get("Route");
				Integer is_left_warning = 0;
				Integer is_right_warning = 0;
				double range = (double) resMap.get("Range");
				Integer is_forward_warning = 0;
				Integer is_backward_warning = 0;
				double height = (double) resMap.get("Height");
				Integer is_up_warning = 0;
				String device_no = lis.get("deviceNo").toString();
				if ((Integer) resMap.get("WarningType") == 202 || (Integer) resMap.get("WarningType") == 102) {
					is_up_warning = 1;
					resMap.put("device_no", device_no);
					resMap.put("api_key", api_key);
					resMap.put("engCode", engCode);
					resMap.put("projectCode", projectCode);
					warning(resMap);
				}
				resMap.put("WarningType", 111);
				double wind_speed = (double) resMap.get("WindSpeed");
				Integer collision_warn = 0;
				if ((Integer) resMap.get("WarningType") == 111 || (Integer) resMap.get("WarningType") == 112
						|| (Integer) resMap.get("WarningType") == 113 || (Integer) resMap.get("WarningType") == 114
						|| (Integer) resMap.get("WarningType") == 211 || (Integer) resMap.get("WarningType") == 212
						|| (Integer) resMap.get("WarningType") == 213 || (Integer) resMap.get("WarningType") == 214) {
					resMap.put("device_no", device_no);
					resMap.put("api_key", api_key);
					resMap.put("engCode", engCode);
					resMap.put("projectCode", projectCode);
					collision_warn = 1;
					warning(resMap);
				}
				Integer wind_warn = 0;
				if (wind_speed > 13.8) {
					resMap.put("device_no", device_no);
					resMap.put("api_key", api_key);
					resMap.put("engCode", engCode);
					resMap.put("projectCode", projectCode);
					wind_warn = 1;
					warning(resMap);
				}
				Integer rotation_warn = 0;
				if ((Integer) resMap.get("WarningType") == 203 || (Integer) resMap.get("WarningType") == 103) {
					resMap.put("device_no", device_no);
					rotation_warn = 1;
					warning(resMap);
				}

				JSONObject list = new JSONObject();
				list.put("device_no", device_no);
				list.put("runtime", runtime);
				list.put("load", load);
				list.put("load_ratio", load_ratio / 100);
				list.put("moment", moment);
				list.put("moment_ratio", moment_ratio / 100);
				list.put("slewing_speed", slewing_speed);
				list.put("is_left_warning", is_left_warning);
				list.put("is_right_warning", is_right_warning);
				list.put("range", range);
				list.put("is_forward_warning", is_forward_warning);
				list.put("is_backward_warning", is_backward_warning);
				list.put("height", height);
				list.put("is_up_warning", is_up_warning);
				list.put("wind_speed", wind_speed);
				list.put("collision_warn", collision_warn);
				list.put("wind_warn", wind_warn);
				list.put("rotation_warn", rotation_warn);
				list.put("card_num", "0");
				list.put("operator_name", "管理员");
				String date = timestamp;
				List<Object> jsonArray = new ArrayList<>();
				jsonArray.add(list);
				System.out.println(jsonArray.toString());
				String signature = SignatureUtil.getSignature(api_key, api_version, engCode, projectCode, date,
						jsonArray.toString());
				Map<String, Object> param = new HashMap<>();
				param.put("api_key", api_key);
				param.put("project_code", projectCode);
				param.put("eng_code", engCode);
				param.put("api_version", api_version);
				param.put("timestamp", date);
				param.put("body", jsonArray);
				param.put("signature", signature);
				JSONObject json2 = new JSONObject(param);
				String a = json2.toJSONString();
				a = HttpUtil.post(GWS_URL + "crane/addRecord", a);
				System.out.println(a);
			}
		}
	}

	public void warning(Map<String, Object> map) {
		String device_no = map.get("device_no").toString();
		String runtime = map.get("RunTime").toString();
		double load = (double) map.get("Weight");
		double load_ratio = (double) map.get("WeightPercent");
		Float moment = (Float) map.get("Moment");
		double moment_ratio = (double) map.get("MomentPercent");
		double slewing_speed = (double) map.get("Route");
		double height = (double) map.get("Height");
		double range = (double) map.get("Range");
		double wind_speed = (double) map.get("WindSpeed");
		String api_key = map.get("api_key").toString();// 秘钥
		String engCode = map.get("engCode").toString();
		String projectCode = map.get("projectCode").toString();// 项目编号
		JSONObject list = new JSONObject();
		list.put("device_no", device_no);
		list.put("load", load);
		list.put("load_ratio", load_ratio);
		list.put("moment", moment);
		list.put("moment_ratio", moment_ratio / 100);
		list.put("slewing_speed", slewing_speed);
		list.put("runtime", runtime);
		list.put("range", range);
		list.put("height", height);
		list.put("wind_speed", wind_speed);
		List<Object> jsonArray = new ArrayList<>();
		jsonArray.add(list);
		Map<String, Object> param = new HashMap<>();
		String date = timestamp;
		String signature = SignatureUtil.getSignature(api_key, api_version, engCode, projectCode, date,
				jsonArray.toString());
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", date);
		param.put("body", jsonArray);
		param.put("signature", signature);
		JSONObject json2 = new JSONObject(param);
		String a = json2.toJSONString();
		a = HttpUtil.post(GWS_URL + "crane/warning", a);
		System.out.println(a);
	}

	@Scheduled(fixedRate = 1000 * 60)
	public void workLoop() {
		List<Map<String, Object>> projectAll = gwsLongGangQuCrane.getProjectAll(null);

		for (Map<String, Object> li : projectAll) {
			Integer id = (Integer) li.get("project_id");
			String api_key = li.get("api_key").toString();// 秘钥
			String api_version = GWSLongGangQuUploadCraneServiceImpl.api_version;
			String engCode = li.get("engCode").toString();
			String projectCode = li.get("projectCode").toString();// 项目编号
			List<Map<String, Object>> deviceList = gwsLongGangQuCrane.getProjectDeviceAll(id);
			for (Map<String, Object> lis : deviceList) {
				Integer online_or_offline = (Integer) lis.get("online_or_offline");
				Map<String, Object> val = gwsLongGangQuCrane.getDeviceVal(lis.get("deviceCode").toString());
				Map<String, Object> map = new HashMap<>();
				Map<String, Object> electrifyMap = new HashMap<>();
				String device_no = lis.get("deviceNo").toString();
				if (online_or_offline == 1 && val == null) {

					map.put("DeviceCode", lis.get("deviceCode").toString());
					map.put("onlineOrOffline", 0);
					String date = timestamp;
					map.put("endTime", timestamp);

					electrifyMap.put("device_no", lis.get("deviceNo"));
					electrifyMap.put("operation", 0);
					electrifyMap.put("runtime", timestamp);
					electrifyMap.put("device_no", device_no);
					electrifyMap.put("api_key", api_key);
					electrifyMap.put("engCode", engCode);
					electrifyMap.put("projectCode", projectCode);
					electrify(electrifyMap);
					gwsLongGangQuCrane.upOnlineOrOffline(map);
					String max_moment_ratio = gwsLongGangQuCrane.getMomentMax(lis.get("deviceCode").toString(),
							lis.get("start_time").toString(), lis.get("end_time").toString());
					JSONObject json = new JSONObject();
					List<Object> jsonArray = new ArrayList<>();
					json.put("device_no", lis.get("deviceNo"));
					json.put("start_time", lis.get("start_time"));
					json.put("end_time", lis.get("end_time"));
					json.put("max_moment_ratio", max_moment_ratio);
					Map<String, Object> param = new HashMap<>();
					jsonArray.add(json);
					String timestamp = GWSLongGangQuUploadCraneServiceImpl.timestamp;
					String signature = SignatureUtil.getSignature(api_key, api_version, engCode, projectCode, timestamp,
							jsonArray.toString());

					param.put("api_key", api_key);
					param.put("project_code", projectCode);
					param.put("eng_code", engCode);
					param.put("api_version", api_version);
					param.put("timestamp", timestamp);
					param.put("body", jsonArray);
					param.put("signature", signature);
					JSONObject json2 = new JSONObject(param);
					String a = json2.toJSONString();
					a = HttpUtil.post(GWS_URL + "crane/workLoop", a);
					System.out.println(a);
				} else if (online_or_offline == 0 && val != null) {
					map.put("DeviceCode", lis.get("deviceCode").toString());
					map.put("onlineOrOffline", 1);
					map.put("startTime", val.get("RunTime"));
					electrifyMap.put("api_key", api_key);
					electrifyMap.put("engCode", engCode);
					electrifyMap.put("projectCode", projectCode);
					gwsLongGangQuCrane.upOnlineOrOffline(map);
					electrifyMap.put("device_no", device_no);
					electrifyMap.put("operation", 1);
					electrifyMap.put("runtime", val.get("RunTime"));
					electrify(electrifyMap);
				}
			}
		}
	}

	public void electrify(Map<String, Object> map) {
		List<Object> list = new ArrayList<>();
		JSONObject json = new JSONObject();
		json.put("device_no", map.get("device_no"));
		json.put("operation", map.get("operation"));
		json.put("runtime", map.get("runtime"));

		String api_key = map.get("api_key").toString();// 秘钥
		String engCode = map.get("engCode").toString();
		String projectCode = map.get("projectCode").toString();// 项目编号
		json.put("api_key", api_key);
		json.put("engCode", engCode);
		json.put("projectCode", projectCode);
		list.add(json);
		Map<String, Object> param = new HashMap<>();
		String date = timestamp;
		String signature = SignatureUtil.getSignature(api_key, api_version, engCode, projectCode, date,
				list.toString());
		param.put("api_key", api_key);
		param.put("project_code", projectCode);
		param.put("eng_code", engCode);
		param.put("api_version", api_version);
		param.put("timestamp", date);
		param.put("body", list);
		param.put("signature", signature);
		JSONObject json2 = new JSONObject(param);
		String a = json2.toJSONString();
		a = HttpUtil.post(GWS_URL + "crane/electrify", a);
		System.out.println(a);
	}

	@Async(value = "asyncExecutor")
	@Scheduled(cron = "* 30 6 * * ? ")
	public void clockIn() throws ParseException, java.text.ParseException {
		List<Map<String, Object>> projectAll = gwsLongGangQuCrane.getProjectAll(null);
		String timestamp = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		for (Map<String, Object> li : projectAll) {
			Integer id = (Integer) li.get("project_id");
			String apiKey = (String) li.get("api_key");
			String engCode = (String) li.get("engCode");
			String projectCode = (String) li.get("projectCode");
			String api_version = "1.0";

			List<Map<String, Object>> deviceList = gwsLongGangQuCrane.getProjectDeviceAll(id);

			for (Map<String, Object> res : deviceList) {
				String deviceNo = (String) res.get("deviceNo");// uuid32位
																// 工务署设备编号
				String deviceCode = (String) res.get("deviceCode");// 供应商设备编号
				String userName = gwsLongGangQuCrane.getCraneUser(deviceCode);
				if (userName == null) {
					userName = "管理员";
				}
				SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd ");
				String date1 = dateFormat1.format(DateUtil.parseCST(new Date().toString())) + "06:00:00";// 早上上班时间

				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.MINUTE, -30);
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				Integer cl1 = RandomUtil.randomInt(-10, 10);
				Integer cl1m = RandomUtil.randomInt(0, 59);
				try {
					cal.setTime(dateFormat.parse(date1));// 这个为6点整早上上班时间
				} catch (java.text.ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				cal.add(Calendar.SECOND, cl1m);
				cal.add(Calendar.MINUTE, cl1);

				String start_time = dateFormat.format(cal.getTime());// 上班时间

				String date = dateFormat1.format(DateUtil.parseCST(new Date().toString())) + "18:00:00";// 下午下班时间
				Integer cl = RandomUtil.randomInt(-2, 10);
				Integer clm = RandomUtil.randomInt(0, 59);
				cal.setTime(dateFormat.parse(date));// 这个为18点下午下班时间
				cal.add(Calendar.MINUTE, cl);
				cal.add(Calendar.SECOND, clm);

				String end_time = dateFormat.format(cal.getTime());// 下班时间

				List<Object> list = new ArrayList<Object>();
				JSONObject mapVal = new JSONObject();
				mapVal.put("start_time", start_time);
				mapVal.put("end_time", end_time);
				mapVal.put("worker_name", userName);
				mapVal.put("device_no", deviceNo);
				list.add(mapVal);

				String body = list.toString();

				String signature = SignatureUtil.getSignature(apiKey, api_version, engCode, projectCode, timestamp,
						body);
				Map<String, Object> param = new HashMap<>();
				param.put("api_key", apiKey);
				param.put("project_code", projectCode);
				param.put("eng_code", engCode);
				param.put("api_version", api_version);
				param.put("timestamp", timestamp);
				param.put("body", list);
				param.put("signature", signature);
				String a = new JSONObject(param).toJSONString();
				a = HttpUtil.post(GWS_URL + "/crane/clockIn", a);
				System.out.println(a);
			}
		}
	}

	public static void main(String[] args) {
	}
}
